//
//  M4PagoChannelCell.swift
//  M4
//
//  Created by YuChuang on 2024/8/28.
//

import UIKit

class M4PagoChannelCell: M4BaseTableViewCell {
    
    @IBOutlet weak var M4PagoChannelView: UIView!
    
    @IBOutlet weak var M4PagoChannelTitle: UILabel!
    
    private var channels: [M4ChannelDataModel] = []
    
    override func awakeFromNib() {
        super.awakeFromNib()
        M4PagoChannelView.layer.cornerRadius = 2
        M4PagoChannelView.layer.masksToBounds = true
    }
    
    override func M4UpdateDataAndUI() {
        channels = data as? [M4ChannelDataModel] ?? []
        var itemViews: [M4ChannelItemView] = []
        for i in 0..<channels.count {
            let item = UINib(nibName: "M4ChannelItemView", bundle: nil).instantiate(withOwner: self).last as! M4ChannelItemView
            itemViews.append(item)
            M4PagoChannelView.addSubview(item)
            item.snp.makeConstraints { make in
                if i == 0 {
                    make.top.equalTo(M4PagoChannelTitle.snp.bottom)
                }
                else {
                    make.top.equalTo(itemViews[i-1].snp.bottom)
                }
                make.left.right.equalToSuperview()
                if i == channels.count - 1 {
                    make.bottom.equalToSuperview()
                }
            }
            if i == channels.count - 1 {
                item.M4ChannelLine.isHidden = true
            }
            item.M4ChannelTips.text = channels[i].WmW == 1 ? "" : "No recomendado, tarifa adicional por servicios extra"
            item.M4ChannelTipsTop.constant = channels[i].WmW == 1 ? 0 : 10
            item.M4ChannelRecommand.isHidden = channels[i].WmW == 1 ? false : true
            item.M4ChannelLogo.sd_setImage(with: URL(string: channels[i].SSuAUh ?? ""), placeholderImage: UIImage(named: "repayment_logo_spe"))
            item.M4ChannelButton.tag = i
            item.M4ChannelButton.addTarget(self, action: #selector(channelChooseAction(sender:)), for: .touchUpInside)
        }
    }
    
    @objc private func channelChooseAction(sender: UIButton) {
        let index = sender.tag
        M4CellActionDelegate?.M4CellAction(M4IDAction(actionType: M4PagoAction.M4ChannelAction.rawValue, actionData: channels[index].SkA))
        sender.M4EventUnavailable = false
    }
    
}
